package database

import java.sql.Connection
import java.sql.DriverManager

/**
 * 数据库连接池
 */
class ConnectionPool(
    private val account: DatabaseAccount,
    private val poolSize: Int = 10
) {
    private val connectionPool: MutableList<Connection> = mutableListOf()

    init {
        Class.forName("com.mysql.cj.jdbc.Driver")

        for (i in 0 until poolSize) {
            connectionPool.add(createConnection())
        }
    }

    @Synchronized
    fun getConnection(): Connection {
        while (connectionPool.isEmpty()) {
            Thread.sleep(100)
        }
        return connectionPool.removeAt(0)
    }

    @Synchronized
    fun releaseConnection(connection: Connection) {
        if (connectionPool.size < poolSize) {
            connectionPool.add(connection)
        } else {
            connection.close()
        }
    }

    private fun createConnection(): Connection {
        return DriverManager.getConnection(
            account.url,
            account.name,
            account.password
        )
    }
}
